﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;

namespace Fast
{
    [SkipScan]
    public static class FastJsonSerializerServiceCollectionExtensions
    {
        /// <summary>
        /// 添加Json序列化
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        internal static IServiceCollection AddFastJsonSerializer(this IServiceCollection services)
        {
            Check.NotNull(services, nameof(services));

            services.Configure<FastJsonOptions>(options =>
            {
                options.Services = services;
            });

            services.AddTransient<IJsonSerializer, FastDefaultJsonSerializer>();
            services.AddTransient<IJsonSerializerProvider, FastSystemTextJsonSerializerProvider>();
            services.AddConfigureOptions<FastSystemTextJsonSerializerOptions>();
            return services;
        }

        /// <summary>
        /// 替换Json序列化提供器
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection ReplaceFastJsonProvider<TProvider>(this IServiceCollection services)
            where TProvider : class
        {
            Check.NotNull(services, nameof(services));

            services.Replace(ServiceDescriptor.Transient(typeof(IJsonSerializerProvider), typeof(TProvider)));

            return services;
        }

        /// <summary>
        /// 替换Json序列化提供器
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configure"></param>
        /// <returns></returns>
        public static IServiceCollection ReplaceFastJsonProvider<TProvider, TOptions>(this IServiceCollection services, Action<TOptions> configure = null)
            where TProvider : class
            where TOptions : class
        {
            Check.NotNull(services, nameof(services));

            services.Configure<TOptions>(configureOptions =>
            {
                configure?.Invoke(configureOptions);
            });

            return services.ReplaceFastJsonProvider<TProvider>();
        }

    }
}
